package com.db.nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NetworkCopyNIOServer extends AbstractCopy {
    public static void main(String[] args) {
        System.out.println("server started");

        ByteBuffer byteBuffer = ByteBuffer.allocate(BYTE_BUFFER_SIZE);

        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress(SERVER_PORT));
            System.out.println("connection started");

            try (SocketChannel socketChannel = serverSocketChannel.accept();
                 FileChannel fileChannel = new FileOutputStream(FILE_2).getChannel()) {
                System.out.println("client connected");

                long startTime = System.currentTimeMillis();

                try {
                    while (socketChannel.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        fileChannel.write(byteBuffer);
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    System.out.println("client disconnected");
                }

                long time = System.currentTimeMillis() - startTime;

                System.out.println("success");
                System.out.println(time + "ms");

            } catch (IOException e) {
                System.out.println("input output exception");
            }
        } catch (IOException e) {
            System.out.println("input output exception");
        }
    }
}
